// ContextSamples.cs
//

using System;
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;
using jQueryApi;
using Xrm.Page;
using System.Net;
using System.Serialization;

namespace SDK.FormScripts
{
    [GlobalMethods]
    internal static class ContextSamples
    {
        [ScriptName("getAuthenticationHeader")]
        static void GetAuthenticationHeader()
        {
            string authenticationHeader = Context.GetAuthenticationHeader();
            Script.Alert(string.Format("The Authentication Header is:\n\n{0}", authenticationHeader));
        }

        [ScriptName("getOrgAndUserInfo")]
        static void GetOrgAndUserInfo()
        {
            string orgName = Context.GetOrgUniqueName();
            string orgLcid = Context.GetOrgLcid().ToString();
            string currentUserLcid = Context.GetUserLcid().ToString();

            string message = string.Format("The current Organization Name is {0}.\nThe current Organization Language Code Id is {1}.\nThe current user's Language Code Id is {2}.", orgName, orgLcid, currentUserLcid);

            Script.Alert(message);
        }

        [ScriptName("isUserSysAdmin")]
        static void IsUserSysAdmin()
        {
            string query = "RoleSet?$top=1&$filter=Name eq 'System Administrator'&$select=RoleId";

            jQuery.Ajax(GetAjaxOptions(query)).Success(delegate(object data)
            {
                Script.Alert(Json.Stringify(data));
            });

        }

        static jQueryAjaxOptions GetAjaxOptions(string oDataQuery)
        {
            jQueryAjaxOptions ajaxOptions = new jQueryAjaxOptions();

            ajaxOptions.Type = HttpVerb.Get.ToString();
            ajaxOptions.ContentType = "application/json; charset=utf-8";
            ajaxOptions.Url = string.Format("{0}/XRMServices/2011/OrganizationData.svc/{1}", Context.GetServerUrl(), oDataQuery);
            ajaxOptions.DataType = "json";
            ajaxOptions.BeforeSend = delegate(jQueryXmlHttpRequest request) { request.SetRequestHeader("Accept", "application/json"); };
            ajaxOptions.Error = delegate(jQueryXmlHttpRequest request, string textStatus, Exception ex) { Script.Alert(string.Format("Error: {0}", ex.Message)); };

            return ajaxOptions;
        }
    }
}
